<?php
/**

 * ECSHOP 管理中心限时抢购管理

 * ============================================================================

 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。

 * 网站地址: http://www.ecshop.com；

 * ----------------------------------------------------------------------------

 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和

 * 使用；不允许对程序代码以任何形式任何目的的再发布。

 * ============================================================================

 * $Author: iron $

 * $Id: flashsale.php 17217 2017-02-24 22:16:08Z iron $

 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

require(ROOT_PATH . 'includes/lib_goods.php');

require(ROOT_PATH . 'includes/lib_flashsale.php');


$exc = new exchange($ecs->table('flashsale'), $db, 'act_id', 'act_name');



/*------------------------------------------------------ */

//-- 活动列表页

/*------------------------------------------------------ */



if ($_REQUEST['act'] == 'list')

{

    admin_priv('flashsale');



    /* 模板赋值 */

    $smarty->assign('full_page',   1);

    $smarty->assign('ur_here',     $_LANG['flashsale_list']);

    $smarty->assign('action_link', array('href' => 'flashsale.php?act=add', 'text' => $_LANG['add_flashsale']));



    $list = flashsale_list();



    $smarty->assign('flashsale_list', $list['item']);

    $smarty->assign('filter',          $list['filter']);

    $smarty->assign('record_count',    $list['record_count']);

    $smarty->assign('page_count',      $list['page_count']);



    $sort_flag  = sort_flag($list['filter']);

    $smarty->assign($sort_flag['tag'], $sort_flag['img']);



    /* 显示商品列表页面 */

    assign_query_info();

    $smarty->display('flashsale_list.htm');

}



/*------------------------------------------------------ */

//-- 分页、排序、查询

/*------------------------------------------------------ */



elseif ($_REQUEST['act'] == 'query')

{

    $list = flashsale_list();

    $smarty->assign('flashsale_list', $list['item']);

    $smarty->assign('filter',          $list['filter']);

    $smarty->assign('record_count',    $list['record_count']);

    $smarty->assign('page_count',      $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);

    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('flashsale_list.htm'), '',

        array('filter' => $list['filter'], 'page_count' => $list['page_count']));

}



/*------------------------------------------------------ */

//-- 删除

/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove')

{

    check_authz_json('flashsale');

    $id = intval($_GET['id']);

    $flashsale = flashsale_info($id);

    if (empty($flashsale))

    {

        make_json_error($_LANG['flashsale_not_exist']);

    }

    $name = $flashsale['act_name'];

    $exc->drop($id);

    /* 记日志 */

    admin_log($name, 'remove', 'flashsale');

    /* 清除缓存 */

    clear_cache_files();

    $url = 'flashsale.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");

    exit;

}



/*------------------------------------------------------ */

//-- 批量操作

/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')

{

    /* 取得要操作的记录编号 */

    if (empty($_POST['checkboxes']))

    {

        sys_msg($_LANG['no_record_selected']);

    }

    else

    {

        /* 检查权限 */

        admin_priv('flashsale');



        $ids = $_POST['checkboxes'];



        if (isset($_POST['drop']))

        {

            /* 删除记录 */

            $sql = "DELETE FROM " . $ecs->table('flashsale') .

                    " WHERE act_id " . db_create_in($ids);

            $db->query($sql);



            /* 记日志 */

            admin_log('', 'batch_remove', 'flashsale');



            /* 清除缓存 */

            clear_cache_files();



            $links[] = array('text' => $_LANG['back_flashsale_list'], 'href' => 'flashsale.php?act=list&' . list_link_postfix());

            sys_msg($_LANG['batch_drop_ok']);

        }

    }

}



/*------------------------------------------------------ */

//-- 修改排序

/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_sort_order')

{

    check_authz_json('flashsale');



    $id  = intval($_POST['id']);

    $val = intval($_POST['val']);



    $sql = "UPDATE " . $ecs->table('flashsale') .

            " SET sort_order = '$val'" .

            " WHERE act_id = '$id' LIMIT 1";

    $db->query($sql);



    make_json_result($val);

}



/*------------------------------------------------------ */

//-- 添加、编辑

/*------------------------------------------------------ */



elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')

{

    /* 检查权限 */

    admin_priv('flashsale');



    /* 是否添加 */

    $is_add = $_REQUEST['act'] == 'add';

    $smarty->assign('form_action', $is_add ? 'insert' : 'update');



    /* 初始化、取得优惠活动信息 */

    if ($is_add)

    {

        $now = time();

        $flashsale = array(

            'act_id'        => 0,

            'act_name'      => '',

            'start_date'    => local_date('Y-m-d', $now + 86400),

            'end_date'      => local_date('Y-m-d', $now + 4 * 86400),

            'start_time'    => local_date('H:i:s', $now),

            'end_time'      => local_date('H:i:s', $now),

            'user_rank'     => '',

            'act_range'     => FAR_ALL,

            'act_range_ext' => '',

            'min_amount'    => 0,

            'max_amount'    => 0,

            'act_type'      => FAT_GOODS,

            'act_type_ext'  => 0,

            'gift'          => array()

        );

    }

    else

    {

        if (empty($_GET['id']))

        {

            sys_msg('invalid param');

        }

        $id = intval($_GET['id']);

        $flashsale = flashsale_info($id);

        if (empty($flashsale))

        {

            sys_msg($_LANG['flashsale_not_exist']);

        }

    }

    $smarty->assign('flashsale', $flashsale);



    /* 取得用户等级 */

    $user_rank_list = array();

    $user_rank_list[] = array(

        'rank_id'   => 0,

        'rank_name' => $_LANG['not_user'],

        'checked'   => strpos(',' . $flashsale['user_rank'] . ',', ',0,') !== false

    );

    $sql = "SELECT rank_id, rank_name FROM " . $ecs->table('user_rank');

    $res = $db->query($sql);

    while ($row = $db->fetchRow($res))

    {

        $row['checked'] = strpos(',' . $flashsale['user_rank'] . ',', ',' . $row['rank_id']. ',') !== false;

        $user_rank_list[] = $row;

    }

    $smarty->assign('user_rank_list', $user_rank_list);



    /* 取得优惠范围 */

    $act_range_ext = array();

    if ($flashsale['act_range'] != FAR_ALL && !empty($flashsale['act_range_ext']))

    {

        if ($flashsale['act_range'] == FAR_CATEGORY)

        {

            $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $ecs->table('category') .

                " WHERE cat_id " . db_create_in($flashsale['act_range_ext']);

        }

        elseif ($flashsale['act_range'] == FAR_BRAND)

        {

            $sql = "SELECT brand_id AS id, brand_name AS name FROM " . $ecs->table('brand') .

                " WHERE brand_id " . db_create_in($flashsale['act_range_ext']);

        }

        else

        {

            $sql = "SELECT goods_id AS id, goods_name AS name FROM " . $ecs->table('goods') .

                " WHERE goods_id " . db_create_in($flashsale['act_range_ext']);

        }

        $act_range_ext = $db->getAll($sql);

    }

    $smarty->assign('act_range_ext', $act_range_ext);



    /* 赋值时间控件的语言 */

    $smarty->assign('cfg_lang', $_CFG['lang']);



    /* 显示模板 */

    if ($is_add)

    {

        $smarty->assign('ur_here', $_LANG['add_flashsale']);

    }

    else

    {

        $smarty->assign('ur_here', $_LANG['edit_flashsale']);

    }

    $href = 'flashsale.php?act=list';

    if (!$is_add)

    {

        $href .= '&' . list_link_postfix();

    }

    $smarty->assign('action_link', array('href' => $href, 'text' => $_LANG['flashsale_list']));

    assign_query_info();

    $smarty->display('flashsale_info.htm');

}



/*------------------------------------------------------ */

//-- 添加、编辑后提交

/*------------------------------------------------------ */



elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')

{

    /* 检查权限 */

    admin_priv('flashsale');



    /* 是否添加 */

    $is_add = $_REQUEST['act'] == 'insert';



    /* 检查名称是否重复 */

    $act_name = sub_str($_POST['act_name'], 255, false);

    if (!$exc->is_only('act_name', $act_name, intval($_POST['id'])))

    {

        sys_msg($_LANG['act_name_exists']);

    }



    /* 检查享受优惠的会员等级 */

    if (!isset($_POST['user_rank']))

    {

        sys_msg($_LANG['pls_set_user_rank']);

    }



    /* 检查优惠范围扩展信息 */

    if (intval($_POST['act_range']) > 0 && !isset($_POST['act_range_ext']))

    {

        sys_msg($_LANG['pls_set_act_range']);

    }



    /* 检查金额上下限 */

    $min_amount = floatval($_POST['min_amount']) >= 0 ? floatval($_POST['min_amount']) : 0;

    $max_amount = floatval($_POST['max_amount']) >= 0 ? floatval($_POST['max_amount']) : 0;

    if ($max_amount > 0 && $min_amount > $max_amount)

    {

        sys_msg($_LANG['amount_error']);

    }



    /* 取得赠品 */

    $gift = array();

    if (intval($_POST['act_type']) == FAT_GOODS && isset($_POST['gift_id']))

    {

        foreach ($_POST['gift_id'] as $key => $id)

        {

            $gift[] = array('id' => $id, 'name' => $_POST['gift_name'][$key], 'price' => $_POST['gift_price'][$key]);

        }

    }

    /* 提交值 */

    $flashsale = array(

        'act_id'        => intval($_POST['id']),

        'act_name'      => $act_name,

        'start_date'    => local_strtotime($_POST['start_date'].' 00:00:00'),

        'end_date'      => local_strtotime($_POST['end_date'].' 23:59:59'),

        'start_time'    => strtosecond($_POST['start_time']),

        'end_time'      => strtosecond($_POST['end_time']),

        'user_rank'     => isset($_POST['user_rank']) ? join(',', $_POST['user_rank']) : '0',

        'act_range'     => intval($_POST['act_range']),

        'act_range_ext' => intval($_POST['act_range']) == 0 ? '' : join(',', $_POST['act_range_ext']),

        'min_amount'    => floatval($_POST['min_amount']),

        'max_amount'    => floatval($_POST['max_amount']),

        'act_type'      => intval($_POST['act_type']),

        'act_type_ext'  => floatval($_POST['act_type_ext']),

        'gift'          => serialize($gift)

    );


    if ($flashsale['act_type'] == FAT_GOODS)

    {

        $flashsale['act_type_ext'] = round($flashsale['act_type_ext']);

    }



    /* 保存数据 */

    if ($is_add)

    {

        $db->autoExecute($ecs->table('flashsale'), $flashsale, 'INSERT');

        $flashsale['act_id'] = $db->insert_id();

    }

    else

    {

        $db->autoExecute($ecs->table('flashsale'), $flashsale, 'UPDATE', "act_id = '$flashsale[act_id]'");

    }



    /* 记日志 */

    if ($is_add)

    {

        admin_log($flashsale['act_name'], 'add', 'flashsale');

    }

    else

    {

        admin_log($flashsale['act_name'], 'edit', 'flashsale');

    }



    /* 清除缓存 */

    clear_cache_files();



    /* 提示信息 */

    if ($is_add)

    {

        $links = array(

            array('href' => 'flashsale.php?act=add', 'text' => $_LANG['continue_add_flashsale']),

            array('href' => 'flashsale.php?act=list', 'text' => $_LANG['back_flashsale_list'])

        );

        sys_msg($_LANG['add_flashsale_ok'], 0, $links);

    }

    else

    {

        $links = array(

            array('href' => 'flashsale.php?act=list&' . list_link_postfix(), 'text' => $_LANG['back_flashsale_list'])

        );

        sys_msg($_LANG['edit_flashsale_ok'], 0, $links);

    }

}



/*------------------------------------------------------ */

//-- 搜索商品

/*------------------------------------------------------ */



elseif ($_REQUEST['act'] == 'search')

{

    /* 检查权限 */

    check_authz_json('flashsale');



    include_once(ROOT_PATH . 'includes/cls_json.php');



    $json   = new JSON;

    $filter = $json->decode($_GET['JSON']);

    $filter->keyword = json_str_iconv($filter->keyword);

    if ($filter->act_range == FAR_ALL)

    {

        $arr[0] = array(

            'id'   => 0,

            'name' => $_LANG['js_languages']['all_need_not_search']

        );

    }

    elseif ($filter->act_range == FAR_CATEGORY)

    {

        $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $ecs->table('category') .

            " WHERE cat_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";

        $arr = $db->getAll($sql);

    }

    elseif ($filter->act_range == FAR_BRAND)

    {

        $sql = "SELECT brand_id AS id, brand_name AS name FROM " . $ecs->table('brand') .

            " WHERE brand_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";

        $arr = $db->getAll($sql);

    }

    else

    {

        $sql = "SELECT goods_id AS id, goods_name AS name FROM " . $ecs->table('goods') .

            " WHERE goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%'" .

            " OR goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";

        $arr = $db->getAll($sql);

    }

    if (empty($arr))

    {

        $arr = array(0 => array(

            'id'   => 0,

            'name' => $_LANG['search_result_empty']

        ));

    }

    make_json_result($arr);

}
